package com.ll.domain.shop.biz.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ll.app.api.req.AddGoodsReqDTO;
import com.ll.base.constant.LlConstants;
import com.ll.base.dto.ApiResultDTO;
import com.ll.base.dto.PageReqDTO;
import com.ll.base.dto.PageResultDTO;
import com.ll.base.enums.ResultCodeEnum;
import com.ll.base.exception.CustomRunTimeException;
import com.ll.base.util.ScalarUtil;
import com.ll.dal.po.ShopPO;
import com.ll.dal.po.UserPO;
import com.ll.domain.shop.base.GoodsBaseService;
import com.ll.domain.shop.biz.GoodsDomainService;
import com.ll.domain.shop.convert.GoodsConvert;
import com.ll.dal.po.GoodsPO;
import com.ll.domain.shop.convert.ShopConvert;
import com.ll.domain.shop.dto.GoodsDTO;
import com.ll.domain.user.base.UserBaseService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@Service
@RequiredArgsConstructor
public class GoodsDomainServiceImpl implements GoodsDomainService {

    private final GoodsBaseService goodsBaseService;
    private final UserBaseService userBaseService;
    private final String GOODS =  "goods/";
    @Override
    public PageResultDTO<GoodsDTO> page(PageReqDTO pageReq) {
        pageReq.initPage();
        IPage iPage = new Page(pageReq.getPageNo(), pageReq.getPageSize());
        iPage = goodsBaseService.page(iPage, new LambdaQueryWrapper<GoodsPO>());
        PageResultDTO<GoodsPO> poPageResult = new PageResultDTO<>(iPage.getRecords(), iPage.getTotal(), pageReq);
        return PageResultDTO.PageBuildDTO(poPageResult, GoodsConvert::PO2DTO);
    }

    @Override
    public void add(AddGoodsReqDTO reqDTO, MultipartFile file) {
        if(file == null){
            throw new CustomRunTimeException(ResultCodeEnum.PARAM_NOT_EXIST);
        }
        UserPO userPO = userBaseService.getById(reqDTO.getCreator());
        GoodsPO goodsPO = GoodsConvert.addGoodsReqDTO2PO(reqDTO);
        goodsPO.setTenantId(userPO.getTenantId());
        goodsBaseService.save(goodsPO);
        String[] split = file.getOriginalFilename().split("\\.");
        String fileName = goodsPO.getId() + ScalarUtil.DEFAULT_DIAN + split[split.length - 1];
        File file1 = new File(LlConstants.FILE_PATH + GOODS + fileName);
        try {
            file.transferTo(file1);
        } catch (IOException e) {
            e.printStackTrace();
        }
        goodsBaseService.updateLogo(goodsPO.getId(), LlConstants.FILE_HTTP_URL_PREFIX + GOODS + fileName);
    }
}
